import React from "react";
import { Button, Form, Input, notification } from "antd";
import { useNavigate } from "react-router";
import service from "@/service/httpAxios";
import styles from "./login.module.scss";

const App: React.FC = () => {
  const useNavigateTo = useNavigate();
  const [api, contextHolder] = notification.useNotification();

  const openNotification = (msg: string, tips: string) => {
    api.open({
      duration: 2,
      message: msg,
      description: tips,
      placement: "top",
    });
  };
  const onFinish = (values: any) => {
    if (values.password !== values.confirmword) {
      openNotification("注册失败", "输入密码与确认密码不一致");
      return;
    }
    service
      .post("/user/register", values)
      .then((res: any) => {
        if (res.code === 201) {
          openNotification("注册成功", "正在前往登录页面...");
          setTimeout(() => {
            useNavigateTo("/login");
          }, 2000);
        }
      })
      .catch((err: any) => {
        openNotification("注册失败", err.data.msg);
      });
  };
  return (
    <div className={styles.root}>
      {contextHolder}
      <div className="align">
        <div className="second">
          <div style={{ textAlign: "center", marginBottom: 20 }}>
            <h3>欢迎注册</h3>
          </div>
          <Form onFinish={onFinish} autoComplete="off">
            <Form.Item
              name="username"
              rules={[{ required: true, message: "请输入名称" }]}
            >
              <Input placeholder="用户名" />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="confirmword"
              rules={[{ required: true, message: "请再次输入密码" }]}
            >
              <Input placeholder="确认密码" />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login"
                style={{ marginTop: 10 }}
              >
                注 册
              </Button>
            </Form.Item>
          </Form>
          <div className="register">
            <p onClick={() => useNavigateTo("/login")}>已有帐号，去登录</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default App;
